package cn.li.security.jwt;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Setter
    private AuthenticationConverter authenticationConverter;
    @Setter
    private AuthenticationManager authenticationManager;
    @Setter
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try{
            //1 取出jwttoken，并组装成Authentication
            Authentication authRequest = authenticationConverter.convert(request);
            if (authRequest == null) {
                //1.1 失败则跳过，交给其他的处理器
                chain.doFilter(request, response);
                return;
            }
            //1.2 成功，则交给provider进行认证
            Authentication authResult = this.authenticationManager.authenticate(authRequest);
            //2.认证成功，放入SecurityContext
            authenticateSuccess(authResult);
        }catch (AuthenticationException failed){
            //3.失败，则抛出authenticationEntryPoint处理
            authenticateFail(failed);
            this.authenticationEntryPoint.commence(request, response, failed);
            return;
        }
        chain.doFilter(request, response);
    }


    private void authenticateSuccess(Authentication authResult){
        SecurityContextHolder.getContext().setAuthentication(authResult);
    }

    private void authenticateFail(AuthenticationException error){
        SecurityContextHolder.clearContext();
    }
}
